import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { TouchableOpacity, Text, StyleSheet, ActivityIndicator } from 'react-native';
import { toast, primaryColor, uploadImage, executor } from '../utils';

const styles = StyleSheet.create({
  spinner: {
    marginRight: 16
  },
  button: {
    color: primaryColor,
    fontSize: 17,
    padding: 14 
  }
});

class FactoryMessageButton extends Component {
  state = {}
  onSubmit = () => {
    const { selectNotes } = this.props.navigation.state.params;
    if (!selectNotes||selectNotes.length===0) return toast('Please select a message');

    executor(this.props.factoryFeedback)
      .then(({res}) => {
        if (res) {
          this.props.navigation.goBack();
          toast('Sent success');
        }
        this.setState({processing: false});
      });
    this.setState({processing: true});
  }
  render() {
    const { processing } = this.state;

    return processing?<ActivityIndicator style={styles.spinner} color={primaryColor}/>:
      <TouchableOpacity onPress={this.onSubmit}>
        <Text style={styles.button}>{this.props.chinese?'提交':'Submit'}</Text>
      </TouchableOpacity>;
  }
}

export default compose(
  graphql(gql`
    mutation factoryFeedback($orderId:String!,$message:String!,$attachments:[String]) {
      factoryFeedback(orderId:$orderId,message:$message,attachments:$attachments)
    }
  `, {
    name: 'factoryFeedback',
    props: ({ownProps:{navigation:{state:{params:{orderId, selectNotes, attachments}}}}, factoryFeedback}) => {
      return {
        factoryFeedback: () => {
          return Promise.all(attachments?attachments.map(uri=>uploadImage(uri)):[])
            .then(uploads => factoryFeedback({
              variables: {
                message: selectNotes.map(item=>item.sendDescription).join('; '),
                orderId,
                attachments: (uploads&&uploads.length>0)?uploads.map(upload=>upload.data):undefined
              }
            }));
        }
      };
    }
  })
)(FactoryMessageButton);